angular.module('BaseServer')

.service('BaseFunction', ['$resource', '$http', 'BaseConst', 'BaseClass', 'BaseEnum', 'ExtDialog', '$injector',
    function($resource, $http, BaseConst, BaseClass, BaseEnum, ExtDialog, $injector){
        return {
            request: function(url, isReturnArray, parameter, successHandle, errHandle){
                if(successHandle == undefined){
                    successHandle = this.successFun;
                }

                if(errHandle == undefined){
                    errHandle = this.errFun;
                }

                var self = this;
                if(isReturnArray){
                    $resource(url, null, { save: { method: 'POST', isArray: true } }).save(parameter, function(res){
                        self.responseFun(res, successHandle, errHandle);
                    }, self.errFun);
                }
                else {
                    $resource(url).save(parameter, function(res){
                        self.responseFun(res, successHandle, errHandle);
                    }, self.errFun);
                }
            },
            //请求别的服务器Json数据
            httpRequest: function(url, parameter, successHandle, errHandle){
                if(successHandle == undefined){
                    successHandle = this.successFun;
                }

                if(errHandle == undefined){
                    errHandle = this.errFun;
                }

                var self = this;
                $http.post(url, parameter).success(
                    function(data, status, headers, config) {
                        if(data.Error){
                            errHandle(data.Error);
                        }
                        else{
                            self.responseFun(data, successHandle, errHandle);
                        }
                    }
                ).error(
                    function(data, status, headers, config) {
                        var newErr = {
                            leval: 5,
                            title: '请求失败',
                            message: data
                        };

                        errHandle(newErr);
                    }
                );
            },
            responseFun: function(res, successHandle, errHandle){
                if(res.Error){
                    if(errHandle){
                        errHandle(res.Error);
                    }
                    else{
                        this.errFun(res.Error);
                    }
                }
                else{
                    successHandle(res.Data);
                }
            },
            successFun: function(data){
            },
            errFun: function(err){
                if(err.status != undefined){
                    if(err.data != null && err.data != undefined){
                        var title = err.data.title;
                        var msg = err.data.message;
                        if (msg != undefined && msg != null) {
                            if(msg.indexOf('E11000') > -1){
                                msg = "主键索引重复"
                            }
                            ExtDialog.alert(msg, title);
                        }
                        else{
                            ExtDialog.alert("服务器内部错误", "服务器错误");
                        }
                    }
                    else{
                        ExtDialog.alert("服务器内部错误", "服务器错误");
                    }
                }
                else{
                    if(err.message != null && err.message.indexOf("E11000") > -1){
                        err.message = "主键索引重复";
                    }
                    if(err.leval == 0){
                        ExtDialog.alert(err.message, err.title);
                    }
                    else{
                        ExtDialog.alert(err.message, err.title);
                    }
                }
            },
            //获取常量枚举
            getEnum: function(enumCode){
                if(enumCode.indexOf (".") > -1){
                    var ary = enumCode.split(".");
                    try{
                        var enum1 = $injector.get(ary[0])[ary[1]];
                        if(enum1){
                            return enum1;
                        }
                        else{
                            return null;
                        }
                    }
                    catch(err){
                        return null;
                    }
                }
                else{
                    return null;
                }
            },
            stringToDateTime: function (dateTime, dateFormat) {
                var returnDateTime;
                if(dateFormat == undefined){
                    dateFormat = BaseEnum.DateTimeFormat.DateTime;
                }

                if (dateTime.length == 0) {
                    return null;
                }

                dateTime = dateTime.replace(/^[^0-9]+|[^0-9]+$/g, '').replace(/[^0-9]+/g, "/");
                var dateNums = dateTime.split('/');
                if(dateNums.length < 3){
                    return null;
                }

                if(dateFormat == BaseEnum.DateTimeFormat.Date){
                    returnDateTime = new Date(dateNums[0], parseInt(dateNums[1]) - 1, dateNums[2]);
                }
                else {
                    var strHour = 0,
                        strMinute = 0,
                        strSecond = 0;

                    if(dateNums.length > 3){
                        strHour = dateNums[3];
                    }
                    if(dateNums.length > 4){
                        strMinute = dateNums[4];
                    }
                    if(dateNums.length > 5){
                        strSecond = dateNums[5];
                    }

                    returnDateTime = new Date(dateNums[0], parseInt(dateNums[1]) - 1, dateNums[2], strHour, strMinute, strSecond);
                }

                if(returnDateTime < BaseConst.DateTime.Min){
                    returnDateTime = BaseConst.DateTime.Min;
                }

                if(returnDateTime > BaseConst.DateTime.Max){
                    returnDateTime = BaseConst.DateTime.Max;
                }

                return returnDateTime;
            },
            dateTimeToString: function(dateTime, dateFormat){
                if(dateFormat == undefined){
                    dateFormat = BaseEnum.DateTimeFormat.DateTime;
                }

                if(dateTime == undefined || dateTime == null || dateTime <= BaseConst.DateTime.Min){
                    return '';
                }

                var returnDateTime,
                    strYear = dateTime.getFullYear().toString(),
                    strMonth, strDate, strHour, strMinute, strSecond;

                if(dateTime.getMonth() + 1 < 10)
                {
                    strMonth = "0" + (dateTime.getMonth() + 1).toString();
                }
                else{
                    strMonth = (dateTime.getMonth() + 1).toString();
                }

                if(dateTime.getDate() < 10)
                {
                    strDate = "0" + dateTime.getDate().toString();
                }
                else{
                    strDate = dateTime.getDate().toString();
                }

                returnDateTime = strYear + '.' + strMonth + '.' + strDate;

                if(dateFormat == BaseEnum.DateTimeFormat.DateTime){
                    if(dateTime.getHours() < 10)
                    {
                        strHour = "0" + dateTime.getHours().toString();
                    }
                    else{
                        strHour = dateTime.getHours().toString();
                    }

                    if(dateTime.getMinutes() < 10)
                    {
                        strMinute = "0" + dateTime.getMinutes().toString();
                    }
                    else{
                        strMinute = dateTime.getMinutes().toString();
                    }

                    if(dateTime.getSeconds() < 10)
                    {
                        strSecond = "0" + dateTime.getSeconds().toString();
                    }
                    else{
                        strSecond = dateTime.getSeconds().toString();
                    }

                    returnDateTime += ' ' + strHour + ':' + strMinute + ':' + strSecond;
                }

                return returnDateTime;
            },
            //获取当前月有多少天
            getMonthDays: function (dateTime) {
                var dt1 = new Date(dateTime.getFullYear(), dateTime.getMonth(), 1);
                var dt2 = new Date(dateTime.getFullYear(), dateTime.getMonth() + 1, 1);

                return (dt2.getTime() - dt1.getTime()) / (24 * 60 * 60 * 1000);
            },

            percentToNumber: function(val){
                return Number(val.replace('%', '')) / 100;
            },
            //获取文本框被选择的文本以及光标位置
            getSelectText: function(element) {
                var positionStart = element.selectionStart;
                var positionEnd = element.selectionEnd;
                var selectLen = positionEnd - positionStart
                var selectText = element.value.substr(positionStart, selectLen);

                return {
                    Start : positionStart,
                    End : positionEnd,
                    Length : selectLen,
                    Text : selectText
                };
            },
            getRound: function(precision, roundType, roundValue, record){
                if(precision != undefined && precision != null){
                    if(precision.constructor === String){
                        try{
                            precision = eval("record." + precision);
                        }
                        catch(e){
                            return null;
                        }
                    }
                }
                else{
                    return null;
                }

                if(roundType != undefined && roundType != null){
                    if(roundType.constructor === String){
                        try{
                            roundType = eval("record." + roundType);
                        }
                        catch(e){
                            roundType = BaseEnum.RoundType.AccondValueRound.Value;
                        }
                    }
                }
                else{
                    roundType = BaseEnum.RoundType.AccondValueRound.Value;
                }
                
                if(roundValue != undefined && roundValue != null){
                    if(roundValue.constructor === String){
                        try{
                            roundValue = eval("record." + roundValue);
                        }
                        catch(e){
                            roundValue = 5;
                        }
                    }
                }
                else{
                    roundValue = 5;
                }

                return new BaseClass.Round(precision, roundType, roundValue);
            },
            loading: function (isDisplay) {
                if (isDisplay) {
                    ExtDialog.showLoading();
                } else {
                    ExtDialog.hideLoading();
                }
            },
            getGuid: function(){
                function S4() {
                   return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
                }

                return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
            },
            alert: function(msg, title) {
                ExtDialog.alert(msg, title);
            },
            tip: function(msg, title) {
                ExtDialog.tip(msg, title);
            },
            confirm: function(msg, title, options) {
                return ExtDialog.confirm(msg, title, options);
            },
            Cookie: {
                getItem: function(name){
                    var reg = new RegExp("(^| )" + encodeURIComponent(name) + "=([^;]*)(;|$)");
                    var arr = document.cookie.match(reg)
                    if(arr){
                        return decodeURIComponent(arr[2]);
                    }
                    else{
                        return null;
                    }
                },
                setItem: function(name, value, expiredDate){
                    if(expiredDate){
                        document.cookie = encodeURIComponent(name) + "="+ encodeURIComponent(value) + ";expires=" + expiredDate.toUTCString() + ";path=/;";
                    }
                    else{
                        document.cookie = encodeURIComponent(name) + "="+ encodeURIComponent(value) + ";path=/;";
                    }
                },
                removeItem: function(name){
                    var expiredDate = new Date();
                    expiredDate.setTime(expiredDate.getTime() - 1);
                    var cookieValue = this.getCookie(name);
                    if(cookieValue != null){
                        this.setCookie(name, cookieValue, expiredDate);
                    }
                }
            },
            LocalStorage: {
                getItem: function(name){
                    var value = localStorage.getItem(name);
                    if(value){
                        value = decodeURIComponent(value);
                    }
                    return value;
                },
                setItem: function(name, value){
                    localStorage.setItem(name, encodeURIComponent(value));
                },
                removeItem: function(name){
                    localStorage.removeItem(name);
                },
                clear: function(){
                    localStorage.clear();
                }
            }
        };
    }
]);
